﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SKYPE4COMLib;

namespace SkypeBotUI
{
    public partial class MainForm : Form
    {
        private Skype skype = new Skype();
        private BotConfig config = BotConfig.GetSection();

        protected IChat SelectedChat
        {
            get
            {
                var chatVisual = (ChatVisual)listBox1.SelectedItem;
                return chatVisual == null ? null : chatVisual.Chat;
            }
        }

        protected IList<IChat> SelectedChats
        {
            get
            {
                var result = new List<IChat>();
                foreach (var item in listBox1.SelectedItems)
                {
                    result.Add(((ChatVisual)item).Chat);
                }
                return result;
            }
        }

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            txtRssUrl.Text = config.RssUrl;

            skype.Attach(5, true);
            IList<ChatVisual> chats = new List<ChatVisual>();
            foreach (var chat in skype.RecentChats)
            {
                chats.Add(new ChatVisual((IChat)chat));
            }

            listBox1.DataSource = chats;
            listBox1.DisplayMember = "FriendlyName";
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            textBox1.Text = string.Empty;

            IChat chat = SelectedChat;
            if (chat != null)
            {
                IChatMessageCollection messages = chat.Messages;
                for(int i = Math.Min(5, messages.Count); i > 1 ; --i)
                {
                    textBox1.Text += messages[i].Body + "\r\n";
                }
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            config.Save();
        }

        private void timerDoWork_Tick(object sender, EventArgs e)
        {
            if (!updateWorker.IsBusy)
            {
                updateWorker.RunWorkerAsync();
            }
        }

        private void btnStartStop_Click(object sender, EventArgs e)
        {
            if (timerDoWork.Enabled)
            {
                btnStartStop.Text = "Start posting RSS updates";
                timerDoWork.Enabled = false;
            }
            else
            {
                btnStartStop.Text = "Stop posting RSS updates";
                timerDoWork.Enabled = true;
            }
        }

        private void updateWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            this.Invoke((Action)delegate { lblStatus.Text = "Checking..."; });

            try
            {
                var rssStream = new RssStream(config.RssUrl);
                var items = rssStream.GetItems();

                var packetMaxDate = config.LastReadMessageDate;

                var chats = (IList<IChat>)this.Invoke((Func<IList<IChat>>)delegate { return this.SelectedChats; });

                if (chats.Count > 0)
                {
                    foreach (var item in items)
                    {
                        if (config.LastReadMessageDate < item.PubDate)
                        {
                            foreach (var chat in chats)
                            {
                                chat.SendMessage(item.ToString());
                            }
                            listBox1.Invoke((Action)delegate { textBox1.Text += "\r\n" + item.ToString(); });

                            if (packetMaxDate < item.PubDate)
                            {
                                packetMaxDate = item.PubDate;
                            }
                        }
                        else
                        {
                            config.LastReadMessageDate = packetMaxDate;
                        }
                    }

                    config.Save();
                }
                this.Invoke((Action)delegate { lblStatus.Text = ""; });
            }
            catch(Exception exception)
            {
                this.Invoke((Action)delegate { lblStatus.Text = exception.Message; });
            }
        }

        private void txtRssUrl_Leave(object sender, EventArgs e)
        {
            config.RssUrl = txtRssUrl.Text;
        }
    }
}
